<template>
  <div class="Editing-articles-container">
    <div class="left">
      <el-form
        ref="elForm"
        :model="articles"
        :rules="rules"
        size="medium"
        label-width="100px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="articles.title" maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="封面" prop="img">
          <el-upload
            class="avatar-uploader"
            action=""
            :show-file-list="false"
            :auto-upload="false"
            :on-change="handleAvatarChange"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="文章分类" prop="category">
          <el-select v-model="articles.category" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <vab-quill v-model="articles.content" :min-height="350"></vab-quill>
        </el-form-item>
        <el-form-item size="large">
          <el-button type="primary" @click="handleSee">预览效果</el-button>
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-popconfirm
            style="margin-left: 10px"
            confirm-button-text="确定"
            cancel-button-text="不用了"
            icon="el-icon-info"
            icon-color="red"
            title="确定要重置内容吗？"
            @onConfirm="resetForm"
          >
            <el-button slot="reference">重置</el-button>
          </el-popconfirm>
          <el-popconfirm
            title="确认保存吗？"
            style="margin-left: 10px"
            @onConfirm="saveForm"
          >
            <el-button slot="reference">保存</el-button>
          </el-popconfirm>
        </el-form-item>
      </el-form>
    </div>
    <el-dialog title="预览效果" :visible.sync="dialogTableVisible">
      <div style="min-height: 60vh">
        <div class="news-content" v-html="articles.content"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { mapGetters, mapActions } from "vuex";
  import { newarticle } from "@/api/article";
  import vabQuill from "@/plugins/vabQuill";
  export default {
    name: "EditingArticles",
    components: {
      vabQuill,
    },
    filters: {
      toDate(nS) {
        if (nS == null) {
          return "无";
        } else {
          let date = new Date(parseInt(nS));
          let Y = date.getFullYear() + "年";
          let M =
            (date.getMonth() + 1 < 10
              ? "0" + (date.getMonth() + 1)
              : date.getMonth() + 1) + "月";
          let D = date.getDate() + "日";
          return Y + M + D;
        }
      },
    },
    data() {
      return {
        dialogTableVisible: false,
        imageUrl: "",
        articles: {
          content: "",
          title: "",
          img: null,
          category: "",
        },
        options: [
          {
            value: "程序人生",
            label: "程序人生",
          },
          {
            value: "游戏开发",
            label: "游戏开发",
          },
          {
            value: "移动开发",
            label: "移动开发",
          },
          {
            value: "研发管理",
            label: "研发管理",
          },
          {
            value: "计算机基础",
            label: "计算机基础",
          },
          {
            value: "运维安全",
            label: "运维安全",
          },
          {
            value: "前端架构",
            label: "前端架构",
          },
          {
            value: "后端架构",
            label: "后端架构",
          },
          {
            value: "算法研发",
            label: "算法研发",
          },
          {
            value: "Python开发",
            label: "Python开发",
          },
          {
            value: "软件测试",
            label: "软件测试",
          },
          {
            value: "Java开发",
            label: "Java开发",
          },
          {
            value: "产品设计",
            label: "产品设计",
          },
          {
            value: "原型设计",
            label: "原型设计",
          },
          {
            value: "音视频开发",
            label: "音视频开发",
          },
          {
            value: "人工智能",
            label: "人工智能",
          },
          {
            value: "软件工程",
            label: "软件工程",
          },
          {
            value: "大数据开发",
            label: "大数据开发",
          },
          {
            value: "操作系统",
            label: "操作系统",
          },
          {
            value: "数据分析",
            label: "数据分析",
          },
        ],
        value: "",
        rules: {
          title: [
            {
              required: true,
              message: "请输入标题",
              trigger: "blur",
            },
          ],
          img: {
            required: true,
            message: "请选择封面",
            trigger: "change",
          },
          category: {
            required: true,
            message: "请选择文章分类",
            trigger: "blur",
          },
          content: [
            {
              required: true,
              message: "请输入编辑器",
              trigger: "blur",
            },
          ],
        },
      };
    },
    computed: {
      ...mapGetters({ article: "articles/article" }),
    },
    created() {
      this.$baseColorfullLoading(1, "正在加载", (loading) => {
        this.get().then((res) => {
          if (res) this.articles = res;
          this.imageUrl = this.articles.img;
          loading.close();
        });
      });
    },
    mounted() {},
    methods: {
      submitForm() {
        this.$refs["elForm"].validate((valid) => {
          if (!valid) return;
          //TODO 提交表单
          this.$baseColorfullLoading(1, "正在提交", (loading) => {
            console.log(this.articles.img);
            let file = this.dataURLtoFile(
              this.articles.img,
              this.articles.title
            );
            var formData = new FormData();
            formData.append("file", file);
            formData.append("content", this.articles.content);
            formData.append("title", this.articles.title);
            formData.append("categories", this.articles.category);
            console.log(formData);
            newarticle(formData).then((res) => {
              console.log(res);
              if (res.code == 500) {
                this.$message({
                  message: res.msg,
                  type: "warnning",
                });
              }
              if (res.code == 200) {
                this.$message({
                  message: "提交成功",
                  type: "success",
                });
                this.$refs["elForm"].resetFields();
                this.del();
                this.imageUrl = null;
              }
            });
            loading.close();
          });
        });
      },
      resetForm() {
        this.$refs["elForm"].resetFields();
        this.del();
        this.imageUrl = null;
        this.$message("已重置内容");
      },
      handleSee() {
        this.$refs["elForm"].validate((valid) => {
          this.$refs.elForm.validateField("content", (errorMsg) => {});
          if (valid) {
            this.dialogTableVisible = true;
          } else {
            return false;
          }
        });
      },
      saveForm() {
        this.$baseColorfullLoading(1, "正在保存", async (loading) => {
          await this.save(this.articles);
          loading.close();
          this.$message({
            message: "保存成功",
            type: "success",
          });
        });
      },
      handleAvatarChange(file) {
        this.blobToBase64(file.raw).then((res) => {
          // 转化后的base64
          this.articles.img = res;
          this.imageUrl = URL.createObjectURL(file.raw);
        });
      },
      blobToBase64(blob) {
        return new Promise((resolve, reject) => {
          const fileReader = new FileReader();
          fileReader.onload = (e) => {
            resolve(e.target.result);
          };
          // readAsDataURL
          fileReader.readAsDataURL(blob);
          fileReader.onerror = () => {
            reject(new Error("blobToBase64 error"));
          };
        });
      },
      dataURLtoFile(dataurl, filename) {
        //将base64转换为文件
        var arr = dataurl.split(","),
          mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length,
          u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, { type: mime });
      },

      ...mapActions({
        save: "articles/saveinLocal",
        get: "articles/getinLocal",
        del: "articles/deltoLocal",
      }),
    },
  };
</script>
<style lang="scss" scoped>
  .Editing-articles-container {
    .news {
      &-title {
        text-align: center;
      }
      &-content {
        ::v-deep {
          p {
            line-height: 30px;
            img {
              display: block;
              margin-right: auto;
              margin-left: auto;
            }
          }
        }
      }
    }
    .vab-quill-content {
      ::v-deep {
        .el-form-item__content {
          line-height: normal;
        }
      }
    }
  }
</style>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 200px;
    height: 150px;
    line-height: 150px;
    text-align: center;
  }
  .avatar {
    width: 200x;
    height: 150px;
    display: block;
  }
</style>
